#include <dbg.h>

#include <cassert>
using namespace std;

class Solution {
public:
    int minOperations(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        int m = unique(nums.begin(), nums.end()) -
                nums.begin();  // 去重后的元素个数
        int res = 0;
        int left = 0;
        for (int right = 0; right < m; right++) {
            while (nums[right] - nums[left] + 1 > n) {  // 保证区间长度不超过 n
                ++left;                                 // 右移左端点
            }
            res = max(res, right - left + 1);  // 计算最长区间长度
        }
        return n - res;
    }
};

int main() {
    Solution s;

    vector<int> nums1 = {4, 2, 5, 3};
    vector<int> nums2 = {1, 2, 3, 5, 6};
    vector<int> nums3 = {1, 10, 100, 1000};

    // assert(s.minOperations(nums1) == 0);
    assert(s.minOperations(nums2) == 1);
    // assert(s.minOperations(nums3) == 3);

    return 0;
}